package com.modules.web;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.modules.annotation.FixedDict;
import com.modules.service.FixedDictPostProcessor;

@Controller
@RequestMapping(value = "/fixedDict")
public class FixedDictController {
	
	@Autowired
	FixedDictPostProcessor		fixedDictProcessor;
	
	@RequestMapping(value = "/{simpleName}", method = RequestMethod.POST)
	@ResponseBody
	public List loadFixedDicts(@PathVariable String simpleName, @RequestParam(value = "excludes", required = false) String excludes) throws Exception {
		List dicts = new ArrayList();
		Map<String, Class<?>> dictClass = fixedDictProcessor.getFixedDictClass();
		//获取simpleName对应的枚举类
		Class<?> clazz = dictClass.get(simpleName);
		if (clazz != null) {
			FixedDict dictAnnotation = AnnotationUtils.findAnnotation(clazz, FixedDict.class);

			List<String> lstExcludes = StringUtils.isNotEmpty(excludes)?Arrays.asList(excludes.split(",")):null;
			
			//通过枚举类获取枚举对象列表
			List lstEO = Arrays.asList(clazz.getEnumConstants());
			for (Object item : lstEO) {
				if (lstExcludes != null && lstExcludes.size() > 0 && lstExcludes.contains(item + "")) {
					continue;
				}
				Method mLabel = clazz.getMethod(dictAnnotation.label(), null);
				Method mValue = clazz.getMethod(dictAnnotation.value(), null);
				dicts.add(new NameValue(mLabel.invoke(item, null) + "", mValue.invoke(item, null) + ""));
			}
		}
		return dicts;
	}

	private class NameValue {
		private String	name;
		private String	value;

		public NameValue(String name, String value) {
			this.name = name;
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public String getValue() {
			return value;
		}
	}
}
